var swagger = require('./swagger');
var writeinto = require('./writeinto');
var formatter = require('./formatter');
var Config = require('./Config');
const { default: checkReservedWord } = require('./utils/checkReservedWord');
const host = Config.SWAGGER_URL;

var entries = [];
let count = 0;


/**
 * 备份
 */
function backup() {
  writeinto.backupApiFolder();
}

/**
 * 循环处理模块信息
 * @param {Array} resources
 */
var tryCount = 0;
function wrapResources(resources) {
  if (resources.length === 0) {
    console.log('');
    // 获取并写入入口文件
    writeinto.writeEntry(formatter.formatEntry(entries), () => {

      console.log('接口生成成功');
    });
    return;
  }
  console.log('');
  console.log('待处理的模块' + resources.length);
  // console.log(resources);
  var resource = resources.shift();
  console.log('准备获取模块信息', host + resource.url);
  swagger
    .getApidocs(host + resource.url)
    .then((api) => {
      // 获取api模块名称，用于生成文件夹
      var apiname = formatter.formatApi(api.basePath);
      console.log('apiname',apiname);
      apiname = checkReservedWord(apiname)
      // 获取api模块地址，用于拼接在url前面
      var apipath = formatter.formatApiPath(api.basePath);
      entries.push(apiname);
      // 创建api接口模块文件夹
      console.log(`正在处理模块【${apiname}】`);
      writeinto.writeApiFolder(apiname);

      // 获取模块下所有分类，每个分类一个文件
      var categories = swagger.getCategories(api.paths);

      Object.keys(categories).forEach((categoryName) => {
        // console.log(categories[categoryName]);
        // 拼接分类文件内容
        writeinto.writeCategory(
          apiname,
          categoryName,
          formatter.formatCategory(categoryName, categories[categoryName], apipath)
        );
      });
      // 获取模块文件内容并写入
      writeinto.writeApiContent(apiname, formatter.formatApiContent(apiname, categories));
      // 循环获取下一个模块
      tryCount = 0;
      wrapResources(resources);
    })
    .catch((err) => {
        console.log(err)
      console.error(host + resource.url + '获取失败');
      tryCount++;
      if (tryCount < 5) {
        //如果获取小于五次，重新获取该模块
        resources.unshift(resource);
      } else {
        tryCount = 0;
      }
      wrapResources(resources);
    });
}

/**
 * 开始执行自动化脚本
 */
function generate() {
  swagger.getSwaggerResources(host + '/swagger-resources').then((resources) => {
    if (!resources || resources.length < 1) {
      // eslint-disable-next-line no-use-before-define
      tryGenerateAgain();
    } else {
      wrapResources(resources);
    }
  });
}

/**
 * 尝试再次获取
 */
function tryGenerateAgain() {
  count++;
  if (count < 10) {
    console.log('尝试第' + count + '次获取数据');
    generate();
  } else {
    console.log('无法获取到数据');
  }
}
// 是否备份
// backup();
// main process
generate();